const sequelize = require("./dbConnect");
const adminModel = require("./models/adminModel");
const bannerModel = require("./models/bannerModel");

const blogTypeModel = require("./models/blogTypeModel");
const articleModel = require("./models/articleModel");

const md5 = require("md5");

(async () => {
  try {
    // 博客和博客分类之间的关联
    blogTypeModel.hasMany(articleModel, {
      foreignKey: "categoryId",
      targetKey: "id",
    });
    articleModel.belongsTo(blogTypeModel, {
      foreignKey: "categoryId",
      targetKey: "id",
      as: "category",
    });

    await sequelize.sync({ alter: true });
    const adminCount = await adminModel.count();
    const bannerCount = await bannerModel.count();
    if (adminCount === 0) {
      await adminModel.create({
        loginId: process.env.DEFAULT_USERNAME,
        username: process.env.DEFAULT_ALIAS,
        password: md5(process.env.DEFAULT_PASSWORD),
      });
      console.log("Default user created!");
    }
    if (bannerCount === 0) {
      await bannerModel.bulkCreate([
        {
          bigImg: "/static/images/bg1_big.jpg",
          midImg: "/static/images/bg1_mid.jpg",
          title: "遇海, 有舟可渡; 遇险, 有险可守。",
        },
        {
          bigImg: "/static/images/bg2_big.jpg",
          midImg: "/static/images/bg2_mid.jpg",
          title: "播种一种信念,收获一种成功。",
        },
        {
          bigImg: "/static/images/bg3_big.jpg",
          midImg: "/static/images/bg3_mid.jpg",
          title: "正人先要正己，无私才能无畏。",
        },
      ]);
      console.log("Default banners created!");
    }
    console.log("Database synced successfully!");
  } catch (err) {
    console.log("Error while syncing database:", err);
  }
})();
